<template>
  <a-card :bordered="false">
      <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="月份">
              <a-month-picker placeholder="请选择月份" style="width: 100%" :allowClear="false" v-model="monthDate" @change="monthDateChange"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="采购大类">
              <a-select
                v-model="queryParam.provisionBroad"
                placeholder="请选择采购大类"
                :showSearch="true"
                :allowClear="true"
                :filterOption="filterOption"
                @change="handleChange"
                :getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}"
              >
                <a-select-option v-for="item in provisionBroadList" :key="item.id" :value="item.id">{{item.categoryName}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="采购小类">
              <a-select
                v-model="queryParam.provisionSmall"
                placeholder="请选择采购小类"
                :showSearch="true"
                :allowClear="true"
                :filterOption="filterOption"
                @change="handleSmallChange"
                :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
              >
                <a-select-option v-for="item in provisionSmallList" :key="item.id" :value="item.id">{{item.categoryName}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="物料名称">
              <select-material-input v-model="queryParam.materialName" :materialFlag="true" :materialSmall="queryParam.provisionSmall" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="规格型号">
              <j-input placeholder="请输入规格型号" v-model="queryParam.specification"></j-input>
            </a-form-item>
          </a-col>
          <!-- <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="采购状态">
              <j-dict-select-tag type="list" v-model="queryParam.purchaseStatus" style="width: 100%" placeholder="请选择采购状态"  dictCode="purchase_status"/>
            </a-form-item>
          </a-col> -->
          <!-- <template v-if="toggleSearchStatus"></template> -->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchResetLoad" icon="reload" style="margin-left: 8px">重置</a-button>
              <!-- <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a> -->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" v-if="false" @click="purchaseMaterialBatch" :disabled="isDisabledAuth('erpPurchaseChecklist:purchase')">采购</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('采购清单')" :disabled="isDisabledAuth('erpPurchaseChecklist:export')">导出</a-button>
      <!-- 高级查询区域 -->
      <!--<j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
      <a-popover title="自定义列" trigger="click" placement="leftBottom">
        <template slot="content">
          <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
            <a-row>
              <template v-for="(item,index) in defColumns">
                <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                  <a-col :span="12" :key="index"><a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox></a-col>
                </template>
              </template>
            </a-row>
          </a-checkbox-group>
        </template>
        <a style="float: right;"><a-icon type="setting" :style="iconStyle"/></a>
      </a-popover>
    </div>
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        :components="draggableComponent"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">
        <template slot="materialName" slot-scope="text,record">
          <a @click.prevent="findMaterialName(record)">{{record.materialName_dictText}}</a>
        </template>
        <template slot="amount" slot-scope="text,record">
          <a @click.prevent="findAmount(record)">{{record.amount}}</a>
        </template>
        <span slot="action" slot-scope="text, record">
          <a-popconfirm title="确定采购吗?" @confirm="() => purchaseApply(record.id)">
            <a-button
              v-if="record.purchaseStatus == '0'"
              size="small"
              type="primary"
              :hidden="isDisabledAuth('erpPurchaseChecklist:purchase')"
              :disabled="isDisabledAuth('erpPurchaseChecklist:purchase')">采购</a-button>
          </a-popconfirm>
        </span>
      </a-table>
    </div>
    <erp-purchase-checklist-list-modal ref="checklist"></erp-purchase-checklist-list-modal>
    <!-- 采购弹窗 -->
    <a-modal v-model="purchaseFlag" title="采购" @ok="purchaseMaterial" :bodyStyle ="{
        'height':'150px',
      }">
      <j-form-container >
        <a-form-model ref="form" :model="applyModel" :rules="validatorRules" slot="detail">
          <a-row :gutter="48" >
            <a-col :span="48">
              <a-form-model-item label="实采价格" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="practicalPrice">
                <a-input-number
                  :max="99999999"
                  :min="0"
                  :precision="2"
                  v-model="applyModel.practicalPrice"
                  placeholder="请输入实采价格"
                  style="width: 100%"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </j-form-container>
    </a-modal>
  </a-card>
</template>
<script>
  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import {getAction, putAction} from '@/api/manage'
  import { mapGetters } from 'vuex';
  import {DisabledAuthFilterMixin} from '@/mixins/DisabledAuthFilterMixin'
  import ErpPurchaseChecklistListModal from './modules/ErpPurchaseChecklistListModal'
  import SelectMaterialInput from '@/views/scy/components/SelectMaterialInput'
  export default {
    name: 'ErpPurchaseChecklistList',
    mixins:[JeecgListMixin, mixinDevice, DisabledAuthFilterMixin],
    components: {
      ErpPurchaseChecklistListModal,
      SelectMaterialInput
    },
    data () {
      return {
        description: '采购清单管理页面',
        //表头
        columns:[],
        //列设置
        settingColumns:[],
        // 列定义
        defColumns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'大类名称',
            align:"center",
            width:200,
            dataIndex: 'provisionBroad_dictText',
          },
          {
            title:'小类名称',
            align:"center",
            width:200,
            dataIndex: 'provisionSmall_dictText',
          },
          {
            title:'物料名称',
            align:"center",
            width:100,
            dataIndex: 'materialName',
            scopedSlots: { customRender: 'materialName' },
          },
          {
            title:'品牌',
            align:"center",
            width:100,
            dataIndex: 'brand'
          },
          {
            title:'规格型号',
            align:"center",
            width:100,
            dataIndex: 'specification',
          },
          {
            title:'单位',
            align:"center",
            width:100,
            dataIndex: 'unit_dictText',
          },
          {
            title:'参考价格（元）',
            align:"center",
            width:100,
            dataIndex: 'referencePrice',
          },
          {
            title:'实采价格（元）',
            align:"center",
            width:100,
            dataIndex: 'practicalPrice',
          },
          {
            title:'申购总数量',
            align:"center",
            dataIndex: 'amount',
            width:100,
            scopedSlots: { customRender: 'amount' },
          },
          {
            title:'实际采购数量',
            align:"center",
            width:100,
            dataIndex: 'warrantAmountCount',
          },
          {
            title:'采购日期',
            align:"center",
            width:100,
            dataIndex: 'disposeTime',
          },
          {
            title:'采购状态',
            align:"center",
            width:100,
            dataIndex: 'purchaseStatus_dictText',
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action' }
          }
        ],
        url: {
          list: "/api/erp/purchase/procurement/erpPurchaseChecklist/list",
          delete: "/api/erp/purchase/procurement/erpPurchaseChecklist/delete",
          deleteBatch: "/api/erp/purchase/procurement/erpPurchaseChecklist/deleteBatch",
          exportXlsUrl: "/api/erp/purchase/procurement/erpPurchaseChecklist/exportXls",
          importExcelUrl: "api/erp/purchase/procurement/erpPurchaseChecklist/importExcel",
          updatePurchaseStatus: "/api/erp/purchase/procurement/erpPurchaseChecklist/updatePurchaseStatus",
          updatePurchaseStatusBatch: "/api/erp/purchase/procurement/erpPurchaseChecklist/updatePurchaseStatusBatch",
          queryProvisionBroadList: "/api/erp/purchase/material/erpMaterialCategory/queryAllParent",
          queryProvisionSmallList: "/api/erp/purchase/material/erpMaterialCategory/queryChildrenByParentId"
        },
        dictOptions:{},
        superFieldList:[],
        monthDate: null,
        provisionBroadList: [],
        provisionSmallList: [],
        validatorRules: {
          practicalPrice: [
              { required: true, message: '请输入实采价格!', trigger: 'blur' }
          ]
        },
        applyModel: {
          id: null,
          practicalPrice: null
        },
        purchaseFlag: false,
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        dataMonthFlag: false,
        dataMonth: null
      }
    },
    created() {
      this.getSuperFieldList();
      this.findProvisionBroadList()
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      ...mapGetters(['userInfo']),
      searchResetLoad() {
        this.provisionSmallList = []
        this.$set(this.queryParam, 'monthDate', null);
        this.$set(this.queryParam, 'purchaseStatus', null);
        this.$set(this.queryParam, 'specification', null);
        this.$set(this.queryParam, 'provisionBroad', undefined);
        this.$set(this.queryParam, 'provisionSmall', undefined);
        this.$set(this.queryParam, 'materialName', undefined);
        this.loadData()
      },
      monthDateChange(date, dateString) {
        this.dataMonth = dateString
        if(this.queryParam.monthDate !== this.dataMonth) {
          this.dataMonthFlag = true
        } else {
          this.dataMonthFlag = false
        }
      },
      findMaterialName(item) {
        this.$router.push({
          path: `/erp/purchase/material/ErpMaterialListDetail/${item.materialName}`
        })
      },
      findAmount(item) {
        this.$refs.checklist.visible = true
        this.$refs.checklist.billIds = item.billIds
      },
      purchaseApply(id) {
        this.$set(this.applyModel, "id", id)
        this.$set(this.applyModel, "practicalPrice", null)
        this.purchaseFlag = true
        this.$refs['form'].clearValidate();
      },
      purchaseMaterial() {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            putAction(that.url.updatePurchaseStatus, {
              id: this.applyModel.id,
              practicalPrice: this.applyModel.practicalPrice,
              purchaseStatus: '1',
              handlerId: this.userInfo().empId
            }).then(res => {
              if (res.success) {
                that.purchaseFlag = false
                that.$message.success(res.message)
                that.loadData()
                if (that.$refs.search != undefined) {
                  that.$refs.search.initDictData();
                }
                if (that.$refs.search2 != undefined) {
                  that.$refs.search2.initDictData();
                }
              } else {
                that.$message.warning(res.message)
              }
            })
          }
        })
      },
      purchaseMaterialBatch() {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！')
        } else {
          var ids = ''
          for (var a = 0; a < this.selectedRowKeys.length; a++) {
            ids += this.selectedRowKeys[a] + ','
          }
          var that = this
          this.$confirm({
            title: '确认采购',
            content: '是否确定采购选中数据?',
            onOk: function () {
              that.loading = true
              putAction(that.url.updatePurchaseStatusBatch, {
                id: ids,
                purchaseStatus: '1',
                handlerId: that.userInfo().empId
              })
                .then(res => {
                  if (res.success) {
                    that.$message.success(res.message)
                    that.loadData()
                    that.onClearSelected()
                    //判断是否有search对象
                    if (that.$refs.search != undefined) {
                      //重置Dict数据
                      that.$refs.search.initDictData();
                    }
                    if (that.$refs.search2 != undefined) {
                      that.$refs.search2.initDictData();
                    }
                  } else {
                    that.$message.warning(res.message)
                  }
                })
                .finally(() => {
                  that.loading = false
                })
            }
          })
        }
      },
      loadData(arg) {
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        // 加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        if(!this.queryParam.monthDate) {
          this.initMonthDate()
        }
        if(this.dataMonthFlag) {
          this.queryParam.monthDate = this.dataMonth
        }
        this.onClearSelected()
        this.dataMonthFlag = false
        var params = this.getQueryParams() // 查询条件
        this.loading = true
        getAction(this.url.list, params).then(res => {
          if (res.success) {
            // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            //判断是否当前页没有数据且不为第一页
            if (this.dataSource.length == 0 && this.ipagination.current != 1) {
              this.ipagination.current = this.ipagination.current - 1
              this.loadData(this.ipagination.current - 1);
            }
            // update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
      },
      initMonthDate() {
        let nowTime = new Date()
        let m = nowTime.getMonth() + 1
        this.monthDate = nowTime.getFullYear() + "-" + (m < 10 ? '0' + m : m)
        this.queryParam.monthDate = this.monthDate
      },
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'provisionBroad',text:'大类名称',dictCode:''})
        fieldList.push({type:'string',value:'provisionSmall',text:'小类名称',dictCode:''})
        fieldList.push({type:'string',value:'materialName',text:'物料名称',dictCode:''})
        fieldList.push({type:'string',value:'specification',text:'规格型号',dictCode:''})
        fieldList.push({type:'int',value:'amount',text:'数量',dictCode:''})
        fieldList.push({type:'string',value:'unit',text:'单位',dictCode:''})
        fieldList.push({type:'date',value:'disposeTime',text:'月份'})
        fieldList.push({type:'string',value:'purchaseStatus',text:'采购状态',dictCode:''})
        this.superFieldList = fieldList
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      findProvisionBroadList() {
        const that = this
        that.provisionBroadList = []
        getAction(this.url.queryProvisionBroadList).then(res => {
          if (res.success) {
            res.result.forEach((res) => {
              that.provisionBroadList.push({ 'id':res.id, 'categoryName':res.categoryName })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      findProvisionSmallList(value) {
        const that = this
        const parentId = value
        getAction(this.url.queryProvisionSmallList, { parentId }).then(res => {
          if (res.success) {
            res.result.forEach((res) => {
              that.provisionSmallList.push({ 'id':res.id, 'categoryName':res.categoryName })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      handleChange(value) {
        this.provisionSmallList = []
        this.$set(this.queryParam, 'provisionSmall', undefined);
        this.$set(this.queryParam, 'materialName', undefined);
        if (!!value) {
          this.findProvisionSmallList(value)
        }
      },
      handleSmallChange(value) {
        this.$set(this.queryParam, 'materialName', undefined);
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
